package com.cn.por.config.security;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.cn.por.util.jwt.JWTUtil;
import cn.hsa.base.web.vo.WrapperResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * 自定义登陆成功处理过滤器，登陆成功返回json格式字符串。
 * @author wen
 *
 */
public class PorAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		response.setContentType("application/json;charset=utf-8");
		/**
		 * 创建token
		 */
		// 提取用户名，准备写入token
        String username = authentication.getName();
        // 提取角色，转为List<String>对象，写入token
        List<String> roles = new ArrayList<>();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority authority : authorities){
            roles.add(authority.getAuthority());
        }
        // 创建token
        String tokenstr = JWTUtil.createToken(username, roles, JWTUtil.DEFAULT_SECRET, true);
        Map<String,String> token = new HashMap<String,String>();
		token.put("token", JWTUtil.TOKEN_PREFIX + tokenstr);
        WrapperResponse<String> result = new WrapperResponse(0,"success","登陆成功",token);
		ObjectMapper om = new ObjectMapper();
		String resStr = om.writeValueAsString(result);
		//response.addHeader("Access-Control-Allow-Credentials", "true");
		response.getWriter().write(resStr);
	}

}
